const app = getApp()
import util from '../../../utils/util'
import {
  GetGriderAll,
  AdminTaskRelease
} from '../../../config/api'

Page({
  data: {
    userInfo:'',
    adminInfo:'',
    imgs: [],
    count: 0,
    compressImgsSizeArr: [],

    event_level: 1,
    level_index: 0,
    levelArr: [{
      id: 1,
      title: '普通事件'
    },
    {
      id: 2,
      title: '重点事件'
    }
    ],

    addr: '', // 事件地点
    content: '', // 事件内容
    isShowPopup: false,
    receiver_list: [],
    helper: '', // 下级id字符串
    h_name: '', // 下级名称 字符串
    type: 1, //接收人类型  1管理员  2 村民
    allCheck: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let adminInfo = wx.getStorageSync('adminInfo')
    let userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo,
      adminInfo
    })
    this.getGriderAll() // 调用接收人函数
  },

  getGriderAll() { // 获取接收人
    let that = this;
    util.apiRequest(GetGriderAll, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('接收人：', r)
      that.setData({
        receiver_list: r.data.data
      })
    })
  },

  onSelectName() {
    this.setData({
      isShowPopup: true
    })
  },

  confirmName() {
    this.setData({
      isShowPopup: false
    })
  },

  checkAll() { // 全选
    let that = this;
    let receiver_list = that.data.receiver_list;
    let idArr = []
    let nameArr = []

    this.setData({
      allCheck: !this.data.allCheck
    })

    for (let i = 0; i < receiver_list.length; ++i) {
      if (this.data.allCheck) {
        receiver_list[i].isChecked = true
        idArr.push(receiver_list[i].id)
        nameArr.push(receiver_list[i].name)
      } else {
        receiver_list[i].isChecked = false
      }
    }

    console.log('全选idArr', idArr)
    let idArrStr = idArr.toString()
    let nameArrStr = nameArr.toString()

    that.setData({
      helper: idArrStr,
      h_name: nameArrStr,
      receiver_list
    })
  },

  checkboxChange(e) { // 选择
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    let namesString = e.detail.value.toString()
    const items = this.data.receiver_list
    const values = e.detail.value

    if (items.length == values.length) { // 选中/取消全选按钮
      this.setData({
        allCheck: true
      })
    } else {
      this.setData({
        allCheck: false
      })
    }

    let idArr = []
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].isChecked = false

      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].name === values[j]) {
          idArr.push(items[i].id)
          items[i].isChecked = true
        }
      }
    }

    console.log('idArr', idArr)
    let idArrStr = idArr.toString()

    this.setData({
      receiver_list: items,
      helper: idArrStr,
      h_name: namesString
    })

  },

  bindChangeLevel: function (e) {
    console.log('事件等级：', e.detail.value)
    let event_level = this.data.levelArr[e.detail.value].id
    this.setData({
      level_index: e.detail.value,
      event_level
    })
  },

  inputAddr(e) {
    console.log(e)
    this.setData({
      addr: e.detail.value
    })
  },

  inputContent(e) {
    console.log(e.detail.value)
    this.setData({
      content: e.detail.value
    })
  },

  formSubmit() {
    if (this.data.h_name == '') {
      wx.showModal({
        showCancel: false,
        content: '请填写接收人',
      })
      return;
    }

    let content = this.data.content.replace(/(^\s*)|(\s*$)/g, "");
    if (!content) {
      wx.showModal({
        showCancel: false,
        content: '请填写内容',
      })
      return;
    }

    let that = this;
    let params = {
      event_level: that.data.event_level,
      nick_name: that.data.userInfo.nickName,
      uid: that.data.adminInfo.id,
      puid: that.data.adminInfo.id,
      u_name: that.data.adminInfo.username,
      p_name: that.data.adminInfo.username,  
      content: that.data.content,
      attach: that.data.imgs,
      helper: that.data.helper,
      h_name: that.data.h_name,
      type: that.data.type,
      addr: that.data.addr,
      vollege_id: that.data.adminInfo.vollege_id,
      town_id: that.data.adminInfo.town_id,
    }

    console.log('参数：', params)

    util.apiRequest(AdminTaskRelease, params).then(r => {
      console.log('提交后', r)
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: r.data.info,
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/pages/grid/admin_issue/admin_issue"
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: r.data.info,
          icon: 'none',
          duration: 2000
        })
      }
    })

  },


  // 上传图片
  chooseImg: function (e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 750,
                maxHeight = 500;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function () {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    quality: 0.5,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              imgs: that.data.imgs
                            })
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },

  // 预览图片
  previewImg: function (e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})